<template>
  <div>
    <a-modal class="form1"
             v-model="dialogVisible"
             title="添加收货地址"
             width="800px"
             :dialog-style="{ top: '15vh' }"
             ok-text="确认"
             cancel-text="取消"
             @ok="handleOk()"
             @cancel="cancelOK()">
      <a-form-model ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="地址"
                               style=""
                               prop="optionsA">
              <a-cascader :options="CityArray"
                          :value="form.optionsA"
                          :load-data="loadData"
                          change-on-select
                          @change="onChangeAddress"
                          placeholder="请选择地址" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="地址详情"
                               style=""
                               prop="detailAddr">
              <a-input v-model="form.detailAddr"
                       placeholder="请输入地址详情" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="地址备注"
                               style=""
                               prop="comment">
              <a-textarea v-model="form.comment"
                          placeholder="请输入地址备注"
                          :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class="foats">
          <a-form-model-item label="邮政编码"
                             prop="postCode"
                             style="width:386px;padding-left:100px">
            <a-input v-model="form.postCode"
                     placeholder="请输入邮政编码"
                     style="width:220px" />
          </a-form-model-item>
          <div class="beDefault">
            <a-checkbox :checked="form.beenDefault"
                        @change="onChangeBeDefault">
              启用收货地址
            </a-checkbox>
          </div>
        </div>
        <div>

        </div>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import '@/assets/css/form.less'
export default {
  name: 'UserEditForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
      clickStatus: true,
      formArr: '',
      //选中省市区
      selectAddressArr: [],
      //api地区数据
      apiData: {},
      //api默认选中地址
      apiAddress: {},
      form: {
        //省
        province: '',
        //省编码
        provinceCode: '',
        //市
        city: '',
        //市编码
        cityCode: '',
        //区
        district: '',
        //区编码
        districtCode: '',
        //街道
        street: '',
        //街道编码
        streetCode: '',
        //详细地址
        detailAddr: '',
        // 地址备注
        comment: '',
        //邮编
        postCode: '',
        //是否默认
        beenDefault: true,
        //选中后数组
        optionsA: [],
      },
      CityArray: [],
      rules: {
        optionsA: [{ required: true, message: '请选择地址' }],
        detailAddr: [{ required: true, message: '请输入详细地址' }],
      },
      dialogVisible: false
    }
  },
  mounted () {
    console.log(123123)
  },
  created () {
  },
  methods: {
    //获取省市区 如果存的没有就走接口获取再存起来 如果有就直接拿存的赋值
    getCity () {
      this.$store.dispatch('unSave/getAreaListSync', {}).then(res => {
        let result = res;
        for (var i = 0; i < result.length; i++) {
          result[i].isLeaf = false
          result[i].label = result[i].name
          result[i].value = result[i].code
          delete result[i].children
        }
        this.CityArray = result
      })

    },
    loadData (selectedOptions) {
      this.selectAddressArr = selectedOptions
      const targetOption = selectedOptions[selectedOptions.length - 1];
      if (targetOption.level !== "street") {
        targetOption.loading = true;
        this.$store.dispatch('unSave/getAreaListSync', {
          code: targetOption.code,
          level: targetOption.level
        }).then(res => {
          let result = res;
          console.log(result, 'result');
          for (var i = 0; i < result.length; i++) {
            result[i].isLeaf = result[i].level === 'street';
            result[i].label = result[i].name;
            result[i].value = result[i].code;
            delete result[i].children;
          }
          console.log(result);
          targetOption.children = result;
          if (result.length === 0) {
            targetOption.isLeaf = true;
          }
          targetOption.loading = false;
          this.CityArray = [...this.CityArray];

        })
      }
    },

    onChangeAddress (val) {
      if (val.length === 0) {
        this.addressArr()
      }
      for (var i = 0; i < this.selectAddressArr.length; i++) {
        if (this.selectAddressArr[i].level === 'province') {
          this.form.province = this.selectAddressArr[i].label
          this.form.provinceCode = this.selectAddressArr[i].value
        }
        if (this.selectAddressArr[i].level === 'city') {
          this.form.city = this.selectAddressArr[i].label
          this.form.cityCode = this.selectAddressArr[i].value
        }
        if (this.selectAddressArr[i].level === 'district') {
          this.form.district = this.selectAddressArr[i].label
          this.form.districtCode = this.selectAddressArr[i].value
        }
      }
      if (val.length === 4) {
        this.$store.dispatch('unSave/getAreaListSync', {
          code: this.form.districtCode,
          level: this.form.district
        }).then(data => {
          console.log(data, 'data');
          for (var i = 0; i < data.length; i++) {
            if (data[i].value === val[3]) {
              this.form.street = data[i].name
              this.form.streetCode = data[i].value
              this.form.optionsA = val
            }
          }
        })
      }
      console.log(val);
    },

    //获取列表
    tenantAddress (selectAddressArr) {
      console.log(selectAddressArr, 'selectAddressArr');
      this.formArr = selectAddressArr || {}
      this.clickStatus = true
    },
    //修改编辑
    getList (item) {
      this.form = JSON.parse(JSON.stringify(item));
      if (!item.optionsA) {
        this.getselectList(item)
        this.setApiAddress(item)
      }
      this.clickStatus = false
    },
    setApiAddress (item) {
      console.log(item, '123123');
      this.apiAddress.province = item.provinceCode
      this.apiAddress.city = item.cityCode
      this.apiAddress.district = item.districtCode
    },
    //获取选中省市区的详情
    getselectList (result) {
      // console.log(result.tenantInvoice);
      console.log(result);
      let requestData = {
        district: result.districtCode,
        city: result.cityCode,
        province: result.provinceCode,
      };
      for (let i in requestData) {
        this.apiRequest(requestData[i], i, result);
      }
    },
    apiRequest (code, type, result) {
      console.log(code, type, 'a1');
      this.$store
        .dispatch("unSave/getAreaListSync", {
          code,
          level: type
        })
        .then((res) => {
          console.log(123123);
          this.apiData[type] = res
          this.apiCallBack(result);
        });
    },
    apiCallBack (result) {
      console.log(this.apiData)
      if (Object.keys(this.apiData).length === 3) {
        let districtData = this.formatOptions(this.apiData.district);
        let cityData = this.formatOptions(this.apiData.city);
        cityData = this.addChildren(
          cityData,
          this.apiAddress.district,
          districtData
        );
        let provinceData = this.formatOptions(this.apiData.province);
        provinceData = this.addChildren(
          provinceData,
          this.apiAddress.city,
          cityData
        );

        let options = this.CityArray;
        options = this.addChildren(
          options,
          this.apiAddress.province,
          provinceData
        );
        this.CityArray = [...options];
        let optionsA = [];
        optionsA.push(result.provinceCode);
        optionsA.push(result.cityCode);
        optionsA.push(result.districtCode);
        optionsA.push(result.streetCode);
        this.$set(this.form, 'optionsA', optionsA);

        console.log(this.form.optionsA);
      }
    },
    addChildren (options, code, childrenData) {
      options.forEach((element) => {
        if (element.code === code) {
          element.children = childrenData;
        }
      });
      return options;
    },
    formatOptions (array) {
      array.map(function (value) {
        value.label = value.name;
        value.value = value.code;
        return value;
      });
      return array;
    },

    //是否默认
    onChangeBeDefault (e) {
      if (!this.form.beenDefault) {
        this.form.beenDefault = e.target.checked
      }
      console.log(this.formArr, 'this.formArr');
      if (this.formArr !== null) {
        if (this.formArr.length !== 0 && this.clickStatus === true) {
          this.form.beenDefault = e.target.checked
        }
      }
    },

    //确定新增
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$emit('confirmAddress', JSON.parse(JSON.stringify(this.form)));
          this.concel()
        }
      })
    },
    //取消新增 如果form表单没值就是新建取消  有值是修改取消
    cancelOK () {
      this.$emit('cancel')
      this.concel()
    },
    //表单清空
    concel () {
      this.$refs.ruleForm.resetFields();
      this.addressArr()
      this.form.beenDefault = true
    },

    //街道赋值清空
    addressArr () {
      this.form.optionsA = []
      this.form.province = '';
      this.form.provinceCode = '';
      this.form.city = '';
      this.form.cityCode = '';
      this.form.district = '';
      this.form.districtCode = '';
      this.form.street = '';
      this.form.streetCode = '';
      this.form.detailAddr = '';
      this.form.comment = '';
      this.form.postCode = '';
    },
  },
  watch: {
    visible (newVal) {
      this.dialogVisible = newVal;
      if (newVal) {
        this.getCity();
      }
    }
  }
}
</script>
<style lang="less" scoped>
.foats {
  position: relative;
}
.beDefault {
  position: absolute;
  right: 260px;
  top: 10px;
}
.drawerForm {
  padding: 20px 20px 80px 30px;
  overflow: hidden;
}
/deep/ .ant-form-explain {
  position: absolute;
}
/deep/ .ant-form-item-label > label {
  color: @colorGreyFont;
  font-size: 12px;
  font-family: PingFangSC, PingFangSC-Regular;
}
/deep/ .ant-form label {
  font-size: 12px;
  color: @colorGreyFont;
}
/deep/ .ant-input {
  color: @colorCommonFont;
}
/deep/ .ant-input::placeholder {
  color: #ccc;
}
/deep/ .ant-form-item {
  font-size: 12px;
}
</style>
